const myTools = {}

// Session
myTools.saveSession = function (key, data) {
    const dataJSON = JSON.stringify(data)
    window.sessionStorage.setItem(key, dataJSON)
}

myTools.getSession = function (key, type) {
    const dataJSON = window.sessionStorage.getItem(key)
    return type === 1 ? dataJSON : JSON.parse(dataJSON)
}

myTools.removeSession = function (key) {
    window.sessionStorage.removeItem(key)
}

myTools.pushSession = function (key, data) {
    const session = window.sessionStorage
    if (!session.getItem(key)) {
        const Arr = [data]
        myTools.saveSession(key, Arr)
    } else {
        const Arr = myTools.getSession(key)
        Arr.push(data)
        myTools.saveSession(key, Arr)
    }
}

// Array Some
myTools.arrSome = function (list, x) {
    let index
    if (typeof x !== 'object') {
        const isSaved = list.some(function (item, idx, array) {
            index = idx
            return item === x
        })
        return isSaved === true ? index : false
    } else {
        const isSaved = list.some(function (item, idx, array) {
            index = idx
            return JSON.stringify(item) === JSON.stringify(x)
        })
        return isSaved === true ? index : false
    }
}

// History
myTools.historyTo = function (a, b) {
    if (b === null) {
        if (a === null || a === 0) {
            window.location.reload()
        } else {
           window.history.go(a)
        }
    } else if (a === -1) {
        window.history.back()
    } else {
        window.history.forward()
    }
}

//String
myTools.subStr_b = function(str, startStr, endStr, x){
	// x: 0->(),  1->[],  2-> [), 3->(]
	let pos_s, pos_e, pos_start, pos_end
	pos_s = str.indexOf(startStr)
	pos_e = str.indexOf(endStr)
	
	switch(x) {
		case 0:
			pos_start = pos_s + startStr.length
			pos_end = pos_e
			break
		case 1:
			pos_start = pos_s
			pos_end = pos_e + endStr.length
			break
		case 2:
			pos_start = pos_s
			pos_end = pos_e
			break
		case 3:
			pos_start = pos_s + startStr.length
			pos_end = pos_e + endStr.length
			break
	}

	return str.slice(pos_start, pos_end)
}

export {
    myTools
}
